// pages/cashWithdrawal/cashWithdrawal.js
import {
  userBalance
} from '../../utils/request/apiurl'
import api from '../../utils/request/api'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    balanceData: {},//返回可提现数据
	uid:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
	  var userInfo=wx.getStorageSync('userInfo')
	  this.setData({
	  	uid:userInfo.uid
	  })
    //获取余额
    api.post(userBalance.balance, {
      uid: this.data.uid||wx.getStorageSync('userInfo').uid
    }).then(res => {
      // console.log(res)
      this.setData({
        balanceData: res
      })
    }).catch(err => {
      wx.showToast({
        title: err.message,
        icon: 'none'
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
	var userInfo=wx.getStorageSync('userInfo')
	this.setData({
		uid:userInfo.uid
	})
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
	wx.showNavigationBarLoading() //在标题栏中显示加载
	this.onLoad()
	setTimeout(function() {
		wx.hideNavigationBarLoading() //完成停止加载
		wx.stopPullDownRefresh() //停止下拉刷新
	}, 1500);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  // 提现记录
  toList() {
    wx.redirectTo({
      url: '../cashWithdrawal-list/cashWithdrawal-list'
    })
  },
  //提现
  toCash: function(e) {
	  // console.log(e)
    let num = e.detail.value.num*100
    //可提现的金额跟输入的金额做判断
    let balance = this.data.balanceData.applyMoney
    // console.log(num)
    if (!num && num <= 0) {
      return wx.showToast({
        title: "请正确填写提现金额",
        icon: 'none',
		    duration:2000
      })
    } else if (balance == 0){
      return wx.showToast({
        title: '可提现的金额为0',
        icon: 'none',
        duration: 2000
      })
    } else if (num <= balance) {
      api.post(userBalance.toCash, {
        uid: this.data.uid||wx.getStorageSync('userInfo').uid,
        money: num
      }).then(res => {
        // console.log(res)
        wx.showToast({
          title: res,
          icon: 'success',
          success: function() {
            setTimeout(function() {
              wx.switchTab({
                url: '../personal-center/personal-center'
              })
            }, 1200)
          }
        })
      }).catch(err => {
        wx.showToast({
          title: err.message,
          icon: 'none'
        })
      })
    } else if (num > balance) {
      wx.showToast({
        title: "余额不足",
        icon: 'none',
		duration:2000
      })
    } else {
      wx.showToast({
        title: "请正确填写提现金额",
        icon: 'none',
		duration:2000
      })
    }
  }
})